<template>
  <view class="container">
    <view class="header">
      <text class="title">微信</text>
      <view class="user-info">
        <text class="username">{{ currentUsername }}</text>
        <view class="logout-btn" @click="handleLogout">
          <text>退出</text>
        </view>
      </view>
    </view>
    
    <view class="content">
      <!-- 聊天列表 -->
      <view class="chat-list">
        <view 
          v-for="(chat, index) in chatList" 
          :key="index"
          class="chat-item"
          @click="goToChat(chat)"
        >
          <view class="avatar">
            <text class="avatar-text">{{ chat.name.charAt(0) }}</text>
          </view>
          <view class="chat-info">
            <view class="chat-header">
              <text class="chat-name">{{ chat.name }}</text>
              <text class="chat-time">{{ formatTime(chat.lastMessageTime) }}</text>
            </view>
            <view class="chat-preview">
              <text class="chat-message">{{ chat.lastMessage }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <view v-if="chatList.length === 0" class="empty">
        <text>暂无聊天记录</text>
      </view>
    </view>
  </view>
</template>

<script>
import api from '../../utils/api.js'

export default {
  data() {
    return {
      currentUserId: '',
      currentUsername: '',
      chatList: []
    }
  },
  onLoad() {
    console.log('页面加载')
    this.checkLogin()
  },
  onShow() {
    // 每次显示页面时刷新用户列表
    if (this.currentUserId) {
      this.loadChatList()
    }
  },
  methods: {
    checkLogin() {
      // 检查是否已登录
      const userId = uni.getStorageSync('userId')
      const username = uni.getStorageSync('username')
      
      if (!userId || !username) {
        // 未登录，跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        })
        return
      }
      
      this.currentUserId = userId
      this.currentUsername = username
      this.loadChatList()
    },
    
    async loadChatList() {
      try {
        // 从后端获取所有用户列表（除了自己）
        const res = await api.getUserList()
        
        if (res.statusCode === 200 && res.data) {
          // 过滤掉当前用户（确保类型一致）
          this.chatList = res.data
            .filter(user => String(user.id) !== String(this.currentUserId))
            .map(user => ({
              id: String(user.id),
              name: user.username,
              lastMessage: '点击开始聊天',
              lastMessageTime: new Date()
            }))
          
          console.log('当前用户ID:', this.currentUserId)
          console.log('用户列表:', this.chatList)
        }
      } catch (e) {
        console.error('加载用户列表失败', e)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    goToChat(chat) {
      uni.navigateTo({
        url: `/pages/chat/chat?userId=${this.currentUserId}&otherUserId=${chat.id}&otherUserName=${chat.name}`
      })
    },
    
    handleLogout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出当前账号吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('userId')
            uni.removeStorageSync('username')
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }
        }
      })
    },
    
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return `${date.getMonth() + 1}-${date.getDate()}`
      }
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  background-color: #ededed;
  display: flex;
  flex-direction: column;
}

.header {
  height: 88rpx;
  background-color: #393a3e;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.title {
  font-size: 32rpx;
  color: #ffffff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.username {
  font-size: 26rpx;
  color: #ffffff;
  opacity: 0.8;
}

.logout-btn {
  padding: 8rpx 20rpx;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 4rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.logout-btn text {
  font-size: 24rpx;
  color: #ffffff;
}

.content {
  flex: 1;
  overflow-y: auto;
}

.chat-list {
  background-color: #ffffff;
}

.chat-item {
  display: flex;
  padding: 20rpx 24rpx;
  border-bottom: 1rpx solid #e5e5e5;
  background-color: #ffffff;
}

.chat-item:active {
  background-color: #d9d9d9;
}

.avatar {
  width: 88rpx;
  height: 88rpx;
  border-radius: 8rpx;
  background-color: #c0c0c0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.avatar-text {
  color: #ffffff;
  font-size: 32rpx;
}

.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.chat-name {
  font-size: 32rpx;
  color: #000000;
}

.chat-time {
  font-size: 24rpx;
  color: #999999;
  flex-shrink: 0;
  margin-left: 20rpx;
}

.chat-preview {
  overflow: hidden;
}

.chat-message {
  font-size: 26rpx;
  color: #999999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999999;
  font-size: 28rpx;
}
</style>
